<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Agentapi_service {
	
	protected $CI;

	public function __construct()
    {	
        $this->CI =& get_instance();
        $this->CI->load->model('Model_m');
		$this->CI->load->model('Agent_m');
		$this->CI->load->model('Device_m');
		$this->CI->load->model('Commission_m');
		$this->CI->load->library('session');
    }

    /**
    *添加代理
    *@param data 代理信息
    */
	public function addAgent($data)
	{	
		if($data['agent_qq']){
			$data['password']=substr(md5($data['agent_qq']),0,6);
		}
		$back=$this->CI->Agent_m->insert($data);
		if($back){
			$result['success'] = success();
			//$data['id']=$this->CI->Agent_m->insert_id();
			$result['agent'] = $data;
		}else{
			$result['success'] = error(4013);
		}
    	return _echo($result);		
	}

	/**
    *修改代理信息
    *@param where 条件
    *@param data  数据
    */
	public function updateAgentByID($where,$data)
	{
		$back=$this->CI->Agent_m->update($where,$data);
		if($back){
			$result['success'] = success();
			$result['info'] = $data;
		}else{
			$result['success'] = error(4008);
		}
    	return _echo($result);
	}

	/**
    *代理登录
    *@param where 条件
    */
	public function getAgentByqqAndPassword($where){
		$result=$this->CI->Agent_m->select($where);
		if($result){
			$this->CI->session->set_userdata(array('agent'=>$result[0]));
			$data['success'] = success();
			$data['tooken'] = jiami($result[0]['id']);
			$data['level'] = $result[0]['agent_level'];
		}else{
			$data['success'] = error(4012);
		}
		return _echo($data);
	}

	public function getAgentById($where){
		$result=$this->CI->Agent_m->select($where);
		return $result[0];
	}


	/**
    *查下级代理
    *@param where 条件
    */
	public function getloweragent($where){
		$result=$this->CI->Agent_m->select($where);
		if($result){
			$data['success'] = success();
			$data['agent'] = $result;
			foreach ($data['agent'] as $key => $value) {
				$moneywhere['agent_user_id']=$value['id'];
        		$money=$this->CI->Commission_m->getAllMoney($moneywhere);
        		if($money){
        			$data['agent'][$key]['money']=$money;
        		}else{
        			$data['agent'][$key]['money']=0;
        		}
        		$deviccewhere['agent2']=$value['id'];
        		$data['agent'][$key]['device']=$this->CI->Device_m->getDevicecount($deviccewhere);
			}
		}else{
			$data['success'] = error(4006);
			$data['agent'] = array();
		}
		return _echo($data);
	}

	/**
    *查下级代理数量
    *@param where 条件
    */
	public function getloweragentnum($where){
		$result=$this->CI->Agent_m->select($where);
		return count($result);
	}

	/**
    *查一级代理或二级代理
    *@param where 条件
    */
	public function getAgentList($where,$page,$limit){
		$orderby=' id desc ';
		$offset=($page-1)*$limit;
		$result=$this->CI->Agent_m->select($where,$orderby,$limit,$offset);
		return $result;
	}
	

}